package com.empire.module.member.controller.admin.warningindividual;

import com.empire.framework.common.pkivo.MessagePushResponse;
import com.empire.framework.common.pkivo.MessageReceiver;
import com.empire.framework.common.pkivo.MessageSendResponse;
import com.empire.framework.common.pkivo.MessageVariable;
import com.empire.framework.security.core.service.PkiVerifyApiClient;
import com.empire.module.member.dal.dataobject.mapconfig.MapConfigDO;
import com.empire.module.member.dal.dataobject.user.MemberUserDO;
import com.empire.module.member.dal.dataobject.warningindividual.UnifiedWarningDTO;
import com.empire.module.member.dal.dataobject.warningindividual.WarningTypeCountDTO;
import com.empire.module.member.service.mapconfig.MapConfigService;
import com.empire.module.member.service.user.MemberUserService;
import com.empire.module.system.api.user.AdminUserApi;
import com.empire.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import java.util.*;
import java.io.IOException;

import com.empire.framework.common.pojo.PageParam;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.common.pojo.CommonResult;
import com.empire.framework.common.util.object.BeanUtils;
import static com.empire.framework.common.pojo.CommonResult.success;

import com.empire.framework.excel.core.util.ExcelUtils;

import com.empire.framework.apilog.core.annotation.ApiAccessLog;
import static com.empire.framework.apilog.core.enums.OperateTypeEnum.*;

import com.empire.module.member.controller.admin.warningindividual.vo.*;
import com.empire.module.member.dal.dataobject.warningindividual.WarningIndividualDO;
import com.empire.module.member.service.warningindividual.WarningIndividualService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Tag(name = "管理后台 - 非聚集预警记录表（1条记录对应1个人的1次预警）")
@RestController
@RequestMapping("/member/warning-individual")
@Validated
public class WarningIndividualController {

    @Resource
    private WarningIndividualService warningIndividualService;
    @Resource
    private MemberUserService memberUserService;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private MapConfigService mapConfigService;


    @PostMapping("/create")
    @Operation(summary = "创建非聚集预警记录表（1条记录对应1个人的1次预警）")
    @PreAuthorize("@ss.hasPermission('member:warning-individual:create')")
    public CommonResult<Long> createWarningIndividual(@Valid @RequestBody WarningIndividualSaveReqVO createReqVO) {
        return success(warningIndividualService.createWarningIndividual(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新非聚集预警记录表（1条记录对应1个人的1次预警）")
    @PreAuthorize("@ss.hasPermission('member:warning-individual:update')")
    public CommonResult<Boolean> updateWarningIndividual(@Valid @RequestBody WarningIndividualSaveReqVO updateReqVO) {
        warningIndividualService.updateWarningIndividual(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除非聚集预警记录表（1条记录对应1个人的1次预警）")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('member:warning-individual:delete')")
    public CommonResult<Boolean> deleteWarningIndividual(@RequestParam("id") Long id) {
        warningIndividualService.deleteWarningIndividual(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得非聚集预警记录表（1条记录对应1个人的1次预警）")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('member:warning-individual:query')")
    public CommonResult<WarningIndividualRespVO> getWarningIndividual(@RequestParam("id") Long id) {
        WarningIndividualDO warningIndividual = warningIndividualService.getWarningIndividual(id);
        return success(BeanUtils.toBean(warningIndividual, WarningIndividualRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得非聚集预警记录表（1条记录对应1个人的1次预警）分页")
    @PreAuthorize("@ss.hasPermission('member:warning-individual:query')")
    public CommonResult<PageResult<WarningIndividualRespVO>> getWarningIndividualPage(@Valid WarningIndividualPageReqVO pageReqVO) {
        PageResult<WarningIndividualDO> pageResult = warningIndividualService.getWarningIndividualPage(pageReqVO);
        PageResult<WarningIndividualRespVO> result = BeanUtils.toBean(pageResult, WarningIndividualRespVO.class);
        for (WarningIndividualRespVO individualRespVO : result.getList()) {
            MemberUserDO user = memberUserService.getUser(individualRespVO.getPersonId());
            individualRespVO.setPersonName(user.getName());
            Integer foreigner = user.getForeigner();
            if (foreigner == 1) {
                individualRespVO.setIdNumber(user.getPassportNumber()+"(护照号)");
            }
            if (foreigner == 2) {
                individualRespVO.setIdNumber(user.getIdcard()+"(身份证号)");
            }
        }
        return success(result);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出非聚集预警记录表（1条记录对应1个人的1次预警） Excel")
    @PreAuthorize("@ss.hasPermission('member:warning-individual:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportWarningIndividualExcel(@Valid WarningIndividualPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<WarningIndividualDO> list = warningIndividualService.getWarningIndividualPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "非聚集预警记录表（1条记录对应1个人的1次预警）.xls", "数据", WarningIndividualRespVO.class,
                        BeanUtils.toBean(list, WarningIndividualRespVO.class));
    }

    /**
     * 单条标记已读
     * @param id 聚集人员记录ID
     */
    @PutMapping("/mark-single-read")
    @Operation(summary = "单条标记已读")
    @PreAuthorize("@ss.hasPermission('member:warning-gather-person:update')") // 复用更新权限
    public CommonResult<Boolean> markSingleRead(@RequestParam("id") Long id) {
        warningIndividualService.markSingleRead(id);
        return success(true);
    }

    /**
     * 批量标记已读
     * @param ids 聚集人员记录ID列表
     */
    @PutMapping("/mark-batch-read")
    @Operation(summary = "批量标记已读")
    @PreAuthorize("@ss.hasPermission('member:warning-gather-person:update')") // 复用更新权限
    public CommonResult<Boolean> markBatchRead(@RequestBody List<Long> ids) { // 接收ID列表
        warningIndividualService.markBatchRead(ids);
        return success(true);
    }

    @GetMapping("/caseLatestWarnPage")
    @Operation(summary = "获得案件最新预警列表")
    public CommonResult<PageResult<UnifiedWarningDTO>> getCaseLatestWarnPage(@Valid LatestWarnPageReqVO pageVO) {
        return success(warningIndividualService.getCaseLatestWarnPage(pageVO));
    }

    @GetMapping("/caseHomeLatestWarnPage")
    @Operation(summary = "获得首页最新预警列表")
    public CommonResult<PageResult<UnifiedWarningDTO>> getHomeCaseLatestWarnPage(@Valid LatestWarnPageReqVO pageVO) {
        return success(warningIndividualService.getHomeLatestWarnPage(pageVO));
    }

    @GetMapping("/personLatestWarnPage")
    @Operation(summary = "获得个人最新预警列表")
    public CommonResult<PageResult<UnifiedWarningDTO>> getPersonLatestWarnPage(@Valid LatestWarnPageReqVO pageVO) {
        return success(warningIndividualService.getPersonLatestWarnPage(pageVO));
    }

    @GetMapping("/presentationLatestWarn")
    @Operation(summary = "预览报告最新预警列表")
    public CommonResult<PageResult<UnifiedWarningDTO>> presentationLatestWarn(@RequestParam("presentationId") Long presentationId) {
        return success(warningIndividualService.presentationLatestWarnPage(presentationId));
    }

    /**
     * 获取今日预警类型统计（用于饼图）
     */
    @GetMapping("/count-today-by-type")
    @Operation(summary = "获取今日预警类型统计")
//    @PreAuthorize("@ss.hasPermission('member:warning-individual:query')")
    public CommonResult<List<WarningTypeCountDTO>> countTodayWarningsByType(
            @RequestParam(value = "caseId", required = false) String caseId) {
        return success(warningIndividualService.countTodayWarningsByType(caseId));
    }

    /**
     * 获取今日首页预警类型统计（用于饼图）
     */
    @GetMapping("/count-home-today-by-type")
    @Operation(summary = "获取首页今日预警类型统计")
//    @PreAuthorize("@ss.hasPermission('member:warning-individual:query')")
    public CommonResult<List<WarningTypeCountDTO>> countHomeTodayWarningsByType() {
        return success(warningIndividualService.countHomeTodayWarningsByType());
    }

    /**
     * 发送消息（对接前端sendMessage接口）
     * 功能：根据预警记录ID，发送钉钉消息给指定人员
     */
    @PutMapping("/send-message")
    @Operation(summary = "发送预警消息（钉钉/短信等）")
    @Parameter(name = "id", description = "预警记录ID", required = true)
    @Parameter(name = "fenceType", description = "预警类型", required = true)
    @Parameter(name = "conditionId", description = "预警条件ID", required = true)
    public CommonResult<Boolean> sendMessage(
            @RequestParam("id") Long id,
            @RequestParam("fenceType") Integer fenceType,
            @RequestParam("conditionId") Long conditionId) {

        // 1. 校验预警记录是否存在
        WarningIndividualDO warning = warningIndividualService.getWarningIndividual(id);
        if (warning == null) {
            return CommonResult.error(404, "预警记录不存在");
        }

        // 2. 获取接收消息的用户信息（例如：根据预警记录中的人员ID查询手机号等）
        String warningConditionId = warning.getWarningConditionId();
        MapConfigDO mapConfig = mapConfigService.getMapConfig(warningConditionId);
        AdminUserRespDTO user = adminUserApi.getUser(Long.parseLong(mapConfig.getCreator()));
        if (user == null || user.getMobile() == null) {
            return CommonResult.error(400, "接收人信息不完整（缺少手机号）");
        }

        // 3. 构建消息参数（根据实际业务场景调整，这里以调用PkiVerifyApiClient为例）
        try {
            // 3.1 构建模板变量（例如：预警内容、时间等）
            List<MessageVariable> variables = new ArrayList<>();
            MessageVariable contentVar = new MessageVariable();
            contentVar.setName("XX");
            contentVar.setValue("李四");
            variables.add(contentVar);

            // 3.2 构建接收人信息
            List<MessageReceiver> receivers = new ArrayList<>();
            MessageReceiver receiver = new MessageReceiver();
            receiver.setTelephone(user.getMobile()); // 接收人手机号（必填）
            receiver.setReceiverName(user.getNickname()); // 接收人姓名（可选）
            receivers.add(receiver);

            // 3.3 调用第三方消息推送接口（例如：钉钉/短信）
            MessageSendResponse response = PkiVerifyApiClient.pushMessage(
                    UUID.randomUUID().toString().replaceAll("-", ""), // 签名编码（根据实际配置）
                    variables, // 模板变量
                    receivers // 接收人列表
            );

            // 4. 处理推送结果
            if (response.getErrorCode() == 0) {
                // 4.1 推送成功：更新预警记录的发送状态（例如：标记为已发送）
//                warningIndividualService.updateMessageStatus(id, 1); // 1=已发送
                return CommonResult.success(true);
            } else {
                return CommonResult.error(500, "消息发送失败：" + response.getErrorMessage());
            }
        } catch (Exception e) {
            // 5. 异常处理
            return CommonResult.error(500, "消息发送异常：" + e.getMessage());
        }
    }


}